import os
import logging
import requests
import time
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# SMTP SETTINGS
SMTP_SERVER = ''
FROM_EMAIL = ''
TO_EMAIL = ''

# SERVER SETTINGS
SERVER = 'http://127.0.0.1:7070'

# SCAN SITES
WORDPRESS_SITES = []
DRUPAL_SITES = []
JOOMLA_SITES = []
VBULLETIN_SITES = []


def mail(html):
    """Send Email"""
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "CMSScan Report - Date: " + \
        time.strftime("%d/%m/%Y") + " Time: " + time.strftime("%H:%M:%S")
    msg['From'] = FROM_EMAIL
    msg['To'] = TO_EMAIL
    # Create the body of the message (a plain-text and an HTML version).
    text = "Report Generated by CMSScan"
    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    msg.attach(part2)
    # Send the message via local SMTP server.
    smtp_server = smtplib.SMTP(SMTP_SERVER)
    # sendmail function takes 3 arguments:
    # sender's address, recipient's address
    # and message to send - here it is sent as one string.
    smtp_server.sendmail(msg['From'], msg['To'], msg.as_string())
    smtp_server.quit()


def start_scan(url, cms):
     # Gets log paths to log to
    log_dir = os.path.dirname(os.path.realpath(__file__))
    log_file = os.path.join(log_dir, "scheduler.log")

    # Handles Logging
    logger = logging.getLogger(__name__)
    hdlr = logging.FileHandler(log_file)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    data = {"url": url, "cms": cms}
    resp = requests.post("http://127.0.0.1:7070/scan",
                         data=data, timeout=10)
    if resp.status_code == 200:
        logger.info(resp.json())
    else:
        logger.error(f'Scan failed for {url} - CMS: {cms}')


def schedule():
    for wpu in WORDPRESS_SITES:
        start_scan(wpu, 'wordpress')
    for dpu in DRUPAL_SITES:
        start_scan(dpu, 'drupal')
    for vbu in VBULLETIN_SITES:
        start_scan(vbu, 'vbulletin')
    for jmu in JOOMLA_SITES:
        start_scan(jmu, 'joomla')

    if SMTP_SERVER:
        mail(
            "<br><br>CMSScan Scan Completed. Access Results here: {SERVER}/scans")


if __name__ == "__main__":
    schedule()
